﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;

using System.Text;
using System.Windows.Forms;
namespace CommonTools
{
    public partial class IntegerTextBox : TextBox
    {
        public IntegerTextBox()
        {
            InitializeComponent();
            this.KeyPress += new KeyPressEventHandler(IntegerTextBox_KeyPress);
            this.Leave += new EventHandler(IntegerTextBox_Leave);
            this.Enter += new EventHandler(IntegerTextBox_Enter);
        }

        void IntegerTextBox_Enter(object sender, EventArgs e)
        {
            this.Text = this.Text.Trim().Replace(",", "");
        }

        void IntegerTextBox_Leave(object sender, EventArgs e)
        {
            try
            {
                long l = long.Parse(this.Text.Trim());
                this.Text = l.ToString("N0");

            }
            catch { this.Text = string.Empty; }
        }
        public long Value
        {
            get
            {
                if (!string.IsNullOrEmpty(this.Text))
                    return long.Parse(this.Text.Trim().Replace(",", "").Replace("%", ""));
                else
                    return 0;
            }
            set
            {

                if (value.Equals(0))
                    this.Text = string.Empty;
                else
                    this.Text = value.ToString("N0");
            }
        }
        void IntegerTextBox_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!(Char.IsDigit(e.KeyChar) || e.KeyChar == '\b')) e.Handled = true;
        }

        public IntegerTextBox(IContainer container)
        {
            container.Add(this);
            InitializeComponent();
            //this.KeyPress += new KeyPressEventHandler(IntegerTextBox_KeyPress);
            //this.Leave += new EventHandler(IntegerTextBox_Leave);
            //this.Enter += new EventHandler(IntegerTextBox_Enter);
            this.TextChanged += new EventHandler(this.Format_TextBox);
        }

        private void Format_TextBox(object sender, EventArgs e)
        {
            string s = ((TextBox)sender).Text.Trim();
            char[] ch = s.ToCharArray();

            StringBuilder sb = new StringBuilder();

            foreach (char c in ch)
            {
                if (Char.IsDigit(c))
                {
                    sb.Append(c);
                }
            }

            if (sb.Length >= 1)
            {
                ((TextBox)sender).Text = Convert.ToDecimal(sb.ToString()).ToString("N0");
                ((TextBox)sender).SelectionStart = ((TextBox)sender).Text.Length;
            }
            else
            {
                ((TextBox)sender).Clear();
            }
        }

    }
}
